<script setup lang="tsx">
import { ref, inject } from 'vue';
import { useI18n } from 'vue-i18n';
import MyTable from '@/components/myTable/index.vue';
import OperatingBox from '@/components/operatingBox/index.vue';
import QueryBox from '@/components/queryBox/index.vue';
import { formGroup } from '@/components/formDialog/FormDialog';
import FormDialogGroup from '@/components/formDialog/FormDialogGroup.vue';
import { Space, Link, MessagePlugin } from 'tdesign-vue-next';
import { AddIcon, SearchIcon } from 'tdesign-icons-vue-next';
import { getList, add, edit, getInfo, Delete } from '@/api/member/bank';
const { t } = useI18n();
const addDateRange = inject<typeof addDateRange>('addDateRange');
const data = ref([]);
const columns = [
  {
    title: '关联用户名',
    colKey: 'username',
  },
  {
    title: '开户名',
    colKey: 'name',
  },
  {
    title: '关联银行',
    colKey: 'bankName',
  },
  {
    title: '银行账户',
    colKey: 'cardNo',
  },
  // {
  //   title: '开户地址',
  //   colKey: 'bankBranchName',
  // },
  {
    title: '绑定日期',
    colKey: 'createTime',
  },
  {
    title: '状态',
    colKey: 'status',
  },
  {
    title: '操作',
    colKey: 'op',
  },
];

const pagination = ref({
  defaultCurrent: 1,
  defaultPageSize: 10,
  total: 0,
});

interface FormDataType {
  username: string | null;
  cardNo: string | null;
  name: string | null;
  uid: string | null;
  pageNum: string | number | null;
  pageSize: string | number | null;
}
const INITIAL_QUERYFORM: FormDataType = {
  username: undefined,
  cardNo: undefined,
  name: undefined,
  uid: undefined,
  pageNum: null,
  pageSize: null,
};
const queryForm = ref({ ...INITIAL_QUERYFORM });

const dateRange = ref<string[]>([]);
const balanceRange = ref<[number | null, number | null]>([null, null]);
const render = () => (
  <>
    <OperatingBox>
      <t-button icon={() => <AddIcon />} onClick={() => unAdd()}>
        新增
      </t-button>
    </OperatingBox>
    <QueryBox onReset={onReset} v-model:defaultCurrent={pagination.value.defaultCurrent} onSearch={unGetList}>
      <t-input v-model={queryForm.value.uid} placeholder="UID" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.username} placeholder="关联账号" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.name} placeholder="开户名" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-input v-model={queryForm.value.cardNo} placeholder="银行账户" style="width: 240px;">
        {{
          prefixIcon: () => <SearchIcon />,
        }}
      </t-input>
      <t-date-range-picker v-model={dateRange.value} placeholder="绑定日期" />
    </QueryBox>
    <MyTable
      columns={columns}
      data={data.value}
      v-model:pagination={pagination.value}
      rowKey="mbId"
      onUnGetList={unGetList}
    >
      {{
        status: (slotProps: any) => (
          <t-tag theme={slotProps.row.status == 1 ? 'primary' : 'danger'} variant="light">
            {slotProps.row.status == 1 ? '正常' : '停用'}
          </t-tag>
        ),
        op: (slotProps: any) => (
          <Space>
            <Link theme="primary" onClick={() => unEdit(slotProps)}>
              修改
            </Link>
            <Link theme="danger" onClick={() => deleteClickOp(slotProps, false)}>
              {t('pages.detailCard.detail.form.delete')}
            </Link>
          </Space>
        ),
      }}
    </MyTable>
  </>
);

const unGetList = async () => {
  try {
    queryForm.value.pageNum = pagination.value.defaultCurrent;
    queryForm.value.pageSize = pagination.value.defaultPageSize;
    const res = await getList({
      ...addDateRange?.(queryForm.value, dateRange.value),
    });
    data.value = res.rows;
    pagination.value = {
      ...pagination.value,
      total: res.total,
    };
  } catch (e) {
    console.log(e);
  }
};

unGetList();

const onReset = () => {
  queryForm.value = { ...INITIAL_QUERYFORM };
  balanceRange.value = [null, null];
  dateRange.value = [];
  unGetList();
};
/** 添加对话框 */
const formObj = new formGroup();
const unAdd = async () => {
  try {
    formObj.show('添加银行卡', {}, '添加银行卡');
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '添加银行卡',
  '添加银行卡',
  {},
  async (body) => {
    await add(body.data);
    unGetList();
  },
  {
    username: [{ required: true, message: '会员账号不能为空', trigger: 'blur' }],
    bankName: [{ required: true, message: '银行名称不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '开户名不能为空', trigger: 'blur' }],
    cardNo: [{ required: true, message: '银行账户不能为空', trigger: 'blur' }],
  },
);

// 详情
const unEdit = async (slotProps: any) => {
  try {
    let res = await getInfo(slotProps.row.mbId);
    formObj.show(
      '编辑银行卡',
      {
        ...res.data,
      },
      '编辑银行卡',
    );
  } catch (e) {
    console.error(e);
    MessagePlugin.error(e);
  }
};

formObj.add<any>(
  '编辑银行卡',
  '编辑银行卡',
  {},
  async (body) => {
    await edit(body.data);
    unGetList();
  },
  {
    bankName: [{ required: true, message: '银行名称不能为空', trigger: 'blur' }],
    cardNo: [{ required: true, message: '银行账户不能为空', trigger: 'blur' }],
  },
);

// 删除
const confirmVisible = ref(false);
const deleteId = ref([]);
const onConfirmDelete = () => {
  let ids = deleteId.value.join(',');
  Delete(ids).then(() => {
    confirmVisible.value = false;
    MessagePlugin.success('删除成功');
    unGetList();
  });
};

const deleteClickOp = (value: any, isSingle: boolean) => {
  if (isSingle && !value.length) {
    MessagePlugin.warning('请先勾选数据');
    return;
  }
  confirmVisible.value = true;
  deleteId.value = isSingle ? value : [value.row.mbId];
};
</script>

<template>
  <div>
    <render />
    <FormDialogGroup :form-obj="formObj">
      <template #default="{ formData, item }">
        <!-- 添加银行卡对话框 -->
        <template v-if="item == '添加银行卡' || item == '编辑银行卡'">
          <t-form-item label="会员账号" name="username" v-if="item == '添加银行卡'">
            <t-input v-model="formData.username" placeholder="请输入会员账号" />
          </t-form-item>
          <t-form-item label="银行名称" name="bankName">
            <t-input v-model="formData.bankName" placeholder="请输入银行名称" />
          </t-form-item>
          <t-form-item label="姓名" name="name" v-if="item == '添加银行卡'">
            <t-input v-model="formData.name" placeholder="请输入姓名" />
          </t-form-item>
          <t-form-item label="银行账户" name="cardNo">
            <t-input v-model="formData.cardNo" placeholder="请输入银行账户" />
          </t-form-item>
          <!-- <t-form-item label="开户地址(支行名称)" name="bankBranchName">
            <t-input v-model="formData.bankBranchName" placeholder="请输入开户地址(支行名称)" />
          </t-form-item> -->
        </template>
      </template>
    </FormDialogGroup>
    <t-dialog
      v-model:visible="confirmVisible"
      header="确认删除当前所选项目？"
      body="删除后，数据将被清空，且无法恢复"
      @confirm="onConfirmDelete"
    />
  </div>
</template>
